<template>
    <div class="app-container">
        <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
            <el-form-item label="危废名称" prop="wasteName">
                <el-input v-model="queryParams.wasteName" placeholder="请输入危废名称" clearable size="small" @keyup.enter.native="handleQuery" />
            </el-form-item>
            <el-form-item label="批次号码" prop="batchNumber">
                <el-input v-model="queryParams.batchNumber" placeholder="请输入批次号码" clearable size="small" @keyup.enter.native="handleQuery" />
            </el-form-item>
            <el-form-item label="申报人">
                <el-input v-model="queryParams.createBy" placeholder="请输入申报人" clearable size="small" @keyup.enter.native="handleQuery" />
            </el-form-item>
            <el-form-item label="申报日期">
                <el-date-picker v-model="daterangeDeclareDate" size="small" style="width: 240px" value-format="yyyy-MM-dd" type="daterange" range-separator="-" start-placeholder="开始日期" end-placeholder="结束日期"></el-date-picker>
            </el-form-item>
            <el-form-item>
                <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
                <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
            </el-form-item>
        </el-form>

        <el-row :gutter="10" class="mb8">
            <el-col :span="1.5">
                <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd" v-hasPermi="['business:wasteDeclare:add']">新增</el-button>
            </el-col>
            <el-col :span="1.5">
                <el-button type="success" plain icon="el-icon-edit" size="mini" :disabled="single || nonEditable" @click="handleUpdate" v-hasPermi="['business:wasteDeclare:edit']">修改</el-button>
            </el-col>
            <el-col :span="1.5">
                <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple || nonEditable" @click="handleDelete" v-hasPermi="['business:wasteDeclare:remove']">删除</el-button>
            </el-col>
            <el-col :span="1.5">
                <el-button type="warning" plain icon="el-icon-download" size="mini" :loading="exportLoading" @click="handleExport" v-hasPermi="['business:wasteDeclare:export']">导出</el-button>
            </el-col>
            <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>

        <el-table v-loading="loading" :data="wasteDeclareList" @selection-change="handleSelectionChange">
            <el-table-column type="selection" width="55" align="center" />
            <el-table-column label="申报ID" align="center" prop="wasteDeclareId" v-if="false" />
            <!-- <el-table-column label="危废ID" align="center" prop="wasteId" /> -->
            <el-table-column label="批次号码" align="center" prop="batchNumber" width="180" />
            <el-table-column label="危废名称" align="center" prop="wasteName" min-width="180" />
            <el-table-column label="危废分类" align="center" prop="wasteTypeName" />
            <el-table-column label="危废形态" align="center" prop="wasteShape" :formatter="wasteShapeFormat" />
            <el-table-column label="包装形式" align="center" prop="packageType" :formatter="packageTypeFormat" />
            <el-table-column label="危险特性" align="center" prop="hazardousCharacteristics" :formatter="hazardousCharacteristicsFormat" />
            <el-table-column label="预估重量" align="center" prop="wasteDiscreetWeight" width="120" />
            <el-table-column label="申报人" align="center" prop="declareBy" width="100" />
            <el-table-column label="申报日期" align="center" prop="declareDate" width="120">
                <template slot-scope="scope">
                    <span>{{
                        parseTime(scope.row.declareDate, "{y}-{m}-{d}")
                    }}</span>
                </template>
            </el-table-column>
            <el-table-column label="备注" align="center" prop="remark" />
            <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
                <template slot-scope="scope">
                    <el-button v-if="scope.row.hasAttachment === true" size="mini" type="text" icon="el-icon-view" @click="handleOpenAttachmentModal(scope.row)" v-hasPermi="['business:wasteDeclare:add']">查看附件</el-button>
                    <el-button v-if="scope.row.status === 10" size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)" v-hasPermi="['business:wasteDeclare:edit']">修改</el-button>
                    <el-button v-if="scope.row.status === 10" size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)" v-hasPermi="['business:wasteDeclare:remove']">删除</el-button>
                </template>
            </el-table-column>
        </el-table>

        <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize" @pagination="getList" />

        <!-- 添加或修改危废申报对话框 -->
        <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
            <el-form ref="form" :model="form" :rules="rules" label-width="80px">
                <el-form-item label="危废名称" prop="wasteId">
                    <treeselect v-model="form.tempWasteID" :options="wasteTypeOptions" :disable-branch-nodes="true" :show-count="true" :disabled="
                            form.wasteDeclareId && form.wasteDeclareId > 0
                        " @input="wasteInput(null, form.tempWasteID)" placeholder="请选择危废" />
                </el-form-item>
                <el-form-item label="预估重量" prop="wasteDiscreetWeight">
                    <el-input-number v-model="form.wasteDiscreetWeight" placeholder="请输入预估重量">
                    </el-input-number>
                </el-form-item>
                <el-form-item label="申报日期" prop="declareDate">
                    <el-date-picker clearable size="small" v-model="form.declareDate" type="date" :picker-options="pickerOptions" value-format="yyyy-MM-dd HH:mm:ss" placeholder="选择申报日期">
                    </el-date-picker>
                </el-form-item>
                <el-form-item label="拆分数量" v-if="!form.wasteDeclareId && isCanSplit">
                    <el-input-number v-model="form.splitCount" placeholder="请输入拆分个数" :precision="0" :step-strictly="true">
                    </el-input-number>
                </el-form-item>
                <el-form-item label="备注" prop="remark">
                    <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" />
                </el-form-item>
                <el-form-item label="附件">
                    <MultiFileUpload v-model="form.fileList" ListType="text" />
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
                <el-button @click="cancel">取 消</el-button>
            </div>
        </el-dialog>
        <el-dialog title="查看附件" :visible.sync="openAttachmentModal" width="500px" append-to-body>
            <el-form ref="form" :model="attachmentForm" label-width="80px">
                <el-form-item label="危废名称" prop="wasteId">
                    <el-input v-model="attachmentForm.wasteName" disabled />
                </el-form-item>
                <el-form-item label="附件">
                    <MultiFileUpload v-model="attachmentForm.fileList" :disabled="true" ListType="text" />
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click="cancelAttachmentModal">关 闭</el-button>
            </div>
        </el-dialog>
    </div>
</template>

<script>
import { mapActions, mapGetters } from "vuex";
import {
    listWasteDeclare,
    getWasteDeclare,
    delWasteDeclare,
    addWasteDeclare,
    updateWasteDeclare,
    exportWasteDeclare,
} from "@/api/business/wasteDeclare";
import { getWasteDetail } from "@/api/system/waste/detail";

import { treeselectAll } from "@/api/system/waste/type";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";

import MultiFileUpload from "@/components/MultiFileUpload";

export default {
    name: "WasteDeclare",
    components: { Treeselect, MultiFileUpload },
    data() {
        return {
            //按钮loading
            buttonLoading: false,
            // 遮罩层
            loading: true,
            // 导出遮罩层
            exportLoading: false,
            // 选中数组
            ids: [],
            // 非单个禁用
            single: true,
            // 非多个禁用
            multiple: true,
            // 显示搜索条件
            showSearch: true,
            // 总条数
            total: 0,
            // 危废申报表格数据
            wasteDeclareList: [],
            // 弹出层标题
            title: "",
            // 是否显示弹出层
            open: false,
            // 申报日期范围
            daterangeDeclareDate: [],

            // 危废分类树选项
            wasteTypeOptions: undefined,
            // 是否可拆分
            isCanSplit: false,
            //  不可编辑
            nonEditable: false,
            // 查询参数
            queryParams: {
                pageNum: 1,
                pageSize: 10,
                wasteId: undefined,
                batchNumber: undefined,
                declareDate: undefined,
            },
            // 表单参数
            form: {},
            // 表单校验
            rules: {
                tempWasteId: [
                    {
                        required: true,
                        message: "危废ID不能为空",
                        trigger: "change",
                    },
                ],
                wasteDiscreetWeight: [
                    {
                        required: true,
                        message: "预估重量不能为空",
                        trigger: "blur",
                    },
                ],
            },
            // 附件表单
            attachmentForm: {},
            // 附件表单是否打开
            openAttachmentModal: false,
            pickerOptions: {
                disabledDate(time) {
                    let curDate = (new Date()).getTime();
                    // 7天
                    let sevenDayMsec = 7 * 24 * 3600 * 1000;
                    let sevenDay = curDate - sevenDayMsec;
                    return time.getTime() > Date.now() || time.getTime() < sevenDay;;
                }
            },
        };
    },
    created() {
        this.getList();
        this.getTreeselect();
        this.initDictData();
    },
    computed: {
        ...mapGetters([
            "packageTypeOptions",
            "handlerMethodOptions",
            "wasteShapeOptions",
            "hazardousCharacteristicsOptions",
        ]),
    },
    methods: {
        ...mapActions({
            initDictData: "initDataForWasteInfoCard",
        }),
        /** 查询危废申报列表 */
        getList() {
            this.loading = true;
            this.queryParams.params = {};
            if (
                null != this.daterangeDeclareDate &&
                "" != this.daterangeDeclareDate
            ) {
                this.queryParams.params["beginDeclareDate"] =
                    this.daterangeDeclareDate[0];
                this.queryParams.params["endDeclareDate"] =
                    this.daterangeDeclareDate[1];
            }
            listWasteDeclare(this.queryParams).then((response) => {
                this.wasteDeclareList = response.rows;
                this.total = response.total;
                this.loading = false;
            });
        },
        /** 查询危废分类下拉树结构 */
        getTreeselect() {
            treeselectAll().then((response) => {
                this.wasteTypeOptions = response.data;
            });
        },
        // 取消按钮
        cancel() {
            this.open = false;
            this.reset();
        },
        // 包装形式字典翻译
        packageTypeFormat(row) {
            return this.selectDictLabel(this.packageTypeOptions, row.packageType);
        },
        // 处置方式字典翻译
        handlerMethodFormat(row) {
            return this.selectDictLabel(
                this.handlerMethodOptions,
                row.handlerMethod
            );
        },
        // 危废形态字典翻译
        wasteShapeFormat(row) {
            return this.selectDictLabel(this.wasteShapeOptions, row.wasteShape);
        },

        // 危险特性字典翻译
        hazardousCharacteristicsFormat(row) {
            return this.selectDictLabels(
                this.hazardousCharacteristicsOptions,
                row.hazardousCharacteristics
            );
        },
        // 表单重置
        reset() {
            this.form = {
                wasteDeclareId: undefined,
                wasteId: undefined,
                tempWasteID: undefined,
                wasteDiscreetWeight: undefined,
                declareDate: this.parseTime(new Date()),
                splitCount: 1,
                remark: undefined,
                fileList: [],
            };
            this.resetForm("form");
        },
        /** 搜索按钮操作 */
        handleQuery() {
            this.queryParams.pageNum = 1;
            this.getList();
        },
        /** 重置按钮操作 */
        resetQuery() {
            this.daterangeDeclareDate = [];
            this.resetForm("queryForm");
            this.handleQuery();
        },
        // 多选框选中数据
        handleSelectionChange(selection) {
            this.ids = selection.map((item) => item.wasteDeclareId);
            this.nonEditable = selection.filter(item => item.status > 10).length > 0
            this.single = selection.length !== 1;
            this.multiple = !selection.length;
        },
        /** 新增按钮操作 */
        handleAdd() {
            this.reset();
            this.open = true;
            this.title = "添加危废申报";
        },
        /** 修改按钮操作 */
        handleUpdate(row) {
            this.loading = true;
            this.reset();
            const wasteDeclareId = row.wasteDeclareId || this.ids;
            getWasteDeclare(wasteDeclareId).then((response) => {
                this.loading = false;
                this.form = response.data;
                this.form.tempWasteID = 0 - this.form.wasteId;
                if (!this.form.fileList) {
                    this.form.fileList = [];
                }
                this.open = true;
                this.title = "修改危废申报";
            });
        },
        /** 提交按钮 */
        submitForm() {
            this.$refs["form"].validate((valid) => {
                if (valid) {
                    this.buttonLoading = true;
                    if (this.form.wasteDeclareId != null) {
                        updateWasteDeclare(this.form).then((response) => {
                            this.buttonLoading = false;
                            this.msgSuccess("修改成功");
                            this.open = false;
                            this.getList();
                        });
                    } else {
                        this.form.wasteId = 0 - this.form.tempWasteID;
                        // this.form.declareDate = this.parseTime(this.form.declareDate);
                        this.form.isCanSplit = this.isCanSplit;
                        addWasteDeclare(this.form).then((response) => {
                            this.buttonLoading = false;
                            this.msgSuccess("新增成功");
                            this.open = false;
                            this.getList();
                        });
                    }
                }
            });
        },
        /** 删除按钮操作 */
        handleDelete(row) {
            const wasteDeclareIds = row.wasteDeclareId || this.ids;
            this.$confirm(
                '是否确认删除危废申报编号为"' + wasteDeclareIds + '"的数据项?',
                "警告",
                {
                    confirmButtonText: "确定",
                    cancelButtonText: "取消",
                    type: "warning",
                }
            )
                .then(() => {
                    this.loading = true;
                    return delWasteDeclare(wasteDeclareIds);
                })
                .then(() => {
                    this.loading = false;
                    this.getList();
                    this.msgSuccess("删除成功");
                })
                .catch(() => { });
        },
        /** 导出按钮操作 */
        handleExport() {
            const queryParams = this.queryParams;
            this.$confirm("是否确认导出所有危废申报数据项?", "警告", {
                confirmButtonText: "确定",
                cancelButtonText: "取消",
                type: "warning",
            })
                .then(() => {
                    this.exportLoading = true;
                    return exportWasteDeclare(queryParams);
                })
                .then((response) => {
                    this.download(response.msg);
                    this.exportLoading = false;
                })
                .catch(() => { });
        },

        /**
         * 危废选中
         */
        wasteInput(node, wasteID) {
            wasteID = 0 - wasteID;
            if (wasteID && wasteID > 0) {
                getWasteDetail(wasteID).then((response) => {
                    const wasteObj = response.data;
                    // this.form.wasteDiscreetWeight = undefined;
                    this.form.splitCount = 1;
                    if (wasteObj.canSplit && wasteObj.canSplit === "Y") {
                        this.isCanSplit = true;
                    } else {
                        this.isCanSplit = false;
                    }
                });
            }
        },

        /** 查看附件 */
        handleOpenAttachmentModal(row) {
            const wasteDeclareId = row.wasteDeclareId;
            this.attachmentForm = { wasteName: "", fileList: [] };
            getWasteDeclare(wasteDeclareId).then((response) => {
                this.loading = false;
                const data = response.data;
                const { wasteName, fileList } = data;
                this.attachmentForm = { wasteName, fileList };
                if (!this.attachmentForm.fileList) {
                    this.attachmentForm.fileList = [];
                }
                this.openAttachmentModal = true;
            }).catch(err => this.openAttachmentModal = true);
        },

        // 附件表单关闭
        cancelAttachmentModal() {
            this.openAttachmentModal = false;
        },
    },
};
</script>